<template>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="板块名称" prop="forumName">
      <el-input :disabled="isAlter" v-model="ruleForm.forumName"></el-input>
    </el-form-item>
    <el-form-item label="板块头像" prop="avatar" required>
      <el-upload
        class="uploader avatar-uploader"
        action="/upload/forum_avatar"
        :show-file-list="false"
        :on-success="handleAvatarUploadSuccess"
        :before-upload="beforeUpload"
      >
        <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar" />
        <i v-else class="el-icon-plus uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="背景图片" prop="bgImg" required>
      <el-upload
        class="uploader bg-img-uploader"
        action="/upload/forum_bg"
        :show-file-list="false"
        :on-success="handleBgUploadSuccess"
        :before-upload="beforeUpload"
      >
        <img v-if="ruleForm.bgImg" :src="ruleForm.bgImg" class="bgImg" />
        <i v-else class="el-icon-plus uploader-icon bgimg-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="板块类别" prop="category" required>
      <el-select
        :disabled="isAlter"
        v-model="ruleForm.category"
        placeholder="请选择板块类别"
      >
        <el-option
          v-for="c in categoryList"
          :key="c.id"
          :label="c.name"
          :value="c.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="板块简介" prop="intro" required>
      <el-input v-model="ruleForm.intro"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">{{
        isAlter ? "保存" : "创建"
      }}</el-button>
      <el-button v-if="!isAlter" @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>
  <script>
import forumApi from "@/axios/forumApi";
export default {
  props: ["forumId"],
  data() {
    return {
      categoryList: [],
      ruleForm: {
        forumName: "",
        intro: "",
        bgImg: "",
        avatar: "",
        category: "",
      },
      rules: {
        forumName: [
          { required: true, message: "请输入板块名称", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
        ],
        avatar: [
          { required: true, message: "请上传板块头像", trigger: "blur" },
        ],
        bgImg: [
          { required: true, message: "请上传板块背景图片", trigger: "blur" },
        ],
        intro: [
          { required: true, message: "请输入板块简介", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      prevData: {},
    };
  },
  computed: {
    isAlter() {
      return this.forumId != undefined;
    },
  },
  methods: {
    getDiffData() {
      let diff = {};
      for (const k in this.ruleForm) {
        if (this.prevData[k] != this.ruleForm[k]) {
          diff[k] = this.ruleForm[k];
        }
      }
      return diff;
    },
    submitForm(formName) {
      if (!this.isAlter) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            forumApi.createForum(this.ruleForm).then(({ data }) => {
              if (data.code == this.$status.SUCCESS_CODE) {
                this.$alert("创建成功", "", {
                  confirmButtonText: "确定",
                  callback: (action) => {
                    this.$router.push({
                      name: "forum",
                      params: { id: data.data },
                    });
                  },
                });
              }
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
        const diff = this.getDiffData();
        if (Object.keys(diff).length == 0) {
          this.$message.warning("未作出更改");
        } else {
          forumApi.save({ forumId: this.forumId, ...diff }).then((r) => {
            this.$message.success("保存成功");
          });
        }
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleAvatarUploadSuccess(res, file) {
      if (res.code === this.$status.SUCCESS_CODE) {
        this.$message.success("上传成功");
        return (this.ruleForm.avatar = res.data);
      }
    },
    handleBgUploadSuccess(res, file) {
      if (res.code === this.$status.SUCCESS_CODE) {
        this.$message.success("上传成功");
        return (this.ruleForm.bgImg = res.data);
      }
    },
    beforeUpload(file) {
      const acceptTypes = ["image/jpeg", "image/jpg", "image/png"];
      const isJPG = acceptTypes.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG,jpeg,png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  created() {
    forumApi.getCategories().then(({ data }) => {
      if (data.code == this.$status.SUCCESS_CODE) {
        this.categoryList = data.data;
      } else this.$message.error("拉取板块列表失败");
    });
    if (this.forumId) {
      forumApi.getForumInfo(this.forumId).then(({ data }) => {
        this.ruleForm.forumName = data.data.forumName;
        this.ruleForm.intro = data.data.intro;
        this.ruleForm.category = data.data.category;
        this.ruleForm.bgImg = data.data.bgImg;
        this.ruleForm.avatar = data.data.avatar;
        this.prevData = { ...this.ruleForm };
      });
    }
  },
};
</script>
<style scoped lang="less">
.el-form {
  margin: 0 auto;
  margin-top: 50px;
  padding-bottom: 50px;
  width: 1000px;
}
.uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.uploader:hover {
  border-color: #409eff;
}
.uploader-icon {
  margin: 0 auto;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.bgimg-uploader-icon {
  width: 500px;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
}
.bg-img-uploader {
  width: 500px;
  height: 178px;
}
.bgImg {
  width: 500px;
  height: 178px;
}
.avatar {
  width: 178px;
  height: 178px;
  // width: 100%;
  // height: 100%;
  display: block;
}
img {
  object-fit: cover;
  object-position: top center;
}
</style>